package com.wxzz.elearing.comment.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.wxzz.elearing.comment.amqp.producer.CommentProducer;
import com.wxzz.elearing.comment.dto.*;
import com.wxzz.elearing.comment.entity.*;
import com.wxzz.elearing.comment.mapper.ApplyStudyTitleTypeMapper;
import com.wxzz.elearing.comment.mapper.CommunityQuestionsAnswersListMapper;
import com.wxzz.elearing.comment.mapper.StudyQuestionsAnswersListMapper;
import com.wxzz.elearing.comment.service.ICommunityCommentService;
import com.wxzz.elearing.comment.service.IStudyCommentService;
import com.wxzz.elearing.comment.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.comment.vo.CommunityAnswersVo;
import com.wxzz.elearing.comment.vo.CommunityQuestionsContentDescVo;
import com.wxzz.elearing.comment.vo.StudyAnswersVo;
import com.wxzz.elearing.comment.vo.StudyQuestionsContentDescVo;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.dto.SystemMessageMqDto;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

import static com.wxzz.elearing.comment.service.impl.StudyGiveLikeServiceImpl.STUDYGIVELIKECOUNT;
import static com.wxzz.elearing.comment.service.impl.StudyGiveLikeServiceImpl.STUDYHEATCOUNT;

@Service
public class StudyCommentServiceImpl implements IStudyCommentService {


    @Autowired
    public MongoTemplate mongoTemplate;

    @Resource
    private StudyQuestionsAnswersListMapper studyQuestionsAnswersListMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CommentProducer commentProducer;

    @Override
    public ReturnVO saveComment(StudyComment comment) {
        comment.setCreateTime(LocalDateTime.now());
        StudyComment insert = mongoTemplate.insert(comment);
        StudyQuestionsAnswersList studyQuestionsAnswersList = studyQuestionsAnswersListMapper.selectById(comment.getArticleId());
        Optional.ofNullable(studyQuestionsAnswersList).ifPresent(e -> {
            //todo 小程序订阅
            SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
            systemMessageMqDto.setMessageDetail("您发布的文章:"+comment.getCommentContent()+"收到了评论信息");
            systemMessageMqDto.setMessageTitle("学以致用");
            systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
                {
                    add(e.getPublishPersonId());
                }
            });
            commentProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        });
        return new ReturnVO("评论成功", insert.getUid());
    }

    @Resource
    private ApplyStudyTitleTypeMapper applyStudyTitleTypeMapper;
    @Autowired
    private IWxUserApiFeign iWxUserApiFeign;
    @Override
    public ReturnVO<StudyQuestionsContentDescVo> listAllComment(Long articleId) {
        Map<String, String> map = redisTemplate.opsForHash().entries(STUDYHEATCOUNT);
        //热度key
        String heatCount = articleId + ":Studyheat";
        if (map.size() != 0) {
            String s = map.get(heatCount);
            if (StringUtil.isNotBlank(s)) {
                int i = Integer.parseInt(s);
                i += 1;
                redisTemplate.opsForHash().put(STUDYHEATCOUNT, heatCount, String.valueOf(i));
            } else {
                redisTemplate.opsForHash().put(STUDYHEATCOUNT, heatCount, "1");
            }
        } else {
            redisTemplate.opsForHash().put(STUDYHEATCOUNT, heatCount, "1");
        }
        StudyQuestionsContentDescVo questionsContentDescVo = new StudyQuestionsContentDescVo();
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("id", articleId);
        StudyQuestionsAnswersList questionsAnswersList = studyQuestionsAnswersListMapper.selectOne(queryWrapper);
        String publishImageUrl = questionsAnswersList.getPublishImageUrl();
//            String s = JSONObject.toJSONString(publishImageUrl);
        List<String> list = JSONObject.parseObject(publishImageUrl, List.class);
        questionsAnswersList.setPublishImageUrlList(list);
        BeanUtils.copyProperties(questionsAnswersList, questionsContentDescVo);

        String artCount = articleId + ":Studycount";
        //获取评论数量
        Query query = new Query();
        query.addCriteria(Criteria.where("articleId").is(articleId));
        questionsContentDescVo.setAnswersCount(mongoTemplate.count(query, "studyCommentCollection"));

        //获取点赞数量
        Map<String, String> map1 = redisTemplate.opsForHash().entries(STUDYGIVELIKECOUNT);
        String str = map1.get(artCount);
        if (StringUtil.isNotBlank(str)) {
            int i = Integer.parseInt(str);
            questionsContentDescVo.setGiveLikeCount(i);
        } else {
            questionsContentDescVo.setGiveLikeCount(0);
        }
        //获取热度
        Map<String, String> map2 = redisTemplate.opsForHash().entries(STUDYHEATCOUNT);
        String num = map2.get(heatCount);
        if (StringUtil.isNotBlank(num)) {
            int i = Integer.parseInt(num);
            questionsContentDescVo.setHeatCount(i);
        } else {
            questionsContentDescVo.setHeatCount(0);
        }
        ApplyStudyTitleType applyStudyTitleType = applyStudyTitleTypeMapper.selectById(questionsAnswersList.getTitleType());
        if(applyStudyTitleType!=null){
            questionsContentDescVo.setTitleType(applyStudyTitleType.getId());
            questionsContentDescVo.setTitleContentText(applyStudyTitleType.getTypeName());
        }

        FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(questionsContentDescVo.getPublishPersonId());
        questionsContentDescVo.setEnterpriseName(feignWxUserDto.getEnterpriseName());
        questionsContentDescVo.setEnterprisePlaceDetail(feignWxUserDto.getEnterprisePlaceDetail());
        questionsContentDescVo.setOrganizationName(feignWxUserDto.getOrganizationName());
        questionsContentDescVo.setIdentityName(feignWxUserDto.getIdentityName());
        questionsContentDescVo.setPhone(feignWxUserDto.getPhone());
        questionsContentDescVo.setNickname(feignWxUserDto.getNickname());
        return new ReturnVO("详情查询成功", questionsContentDescVo);
    }

//    @Override
//    public ReturnVO setAccept(StudyQuestionsAnswersDto questionsAnswersDto) {
////        String uid = questionsAnswersDto.getUid();
////        Query query = new Query();
////        query.addCriteria(Criteria.where("_id").is(uid));
////        Comment comment = mongoTemplate.findById(query, Comment.class);
//
//        QueryWrapper queryWrapper = new QueryWrapper();
//        queryWrapper.eq("id", questionsAnswersDto.getId());
//        StudyQuestionsAnswersList result = studyQuestionsAnswersListMapper.selectOne(queryWrapper);
//        if (result.getIsAccept() != 0) {
//            ReturnVO returnVO = new ReturnVO();
//            returnVO.setCode("500");
//            returnVO.setMessage("该问题已采纳了其他答案!");
//            return returnVO;
//        }
//        studyQuestionsAnswersListMapper.setAccept(questionsAnswersDto);
//        return new ReturnVO("采纳成功", null);
//    }

    public ReturnVO<JgPageVo<List<StudyComment>>> answersDescList(StudyAnswersDescDto answersDescDto) {
//        PageHelper.startPage(answersDescDto.getCurPage(), answersDescDto.getMaxPage());
        List<StudyComment> list = new ArrayList();

        Query query2 = new Query();
        query2.with(new Sort(Sort.Direction.DESC, "createTime")).with(new PageRequest(answersDescDto.getCurPage()-1, answersDescDto.getMaxPage()));
        query2.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()));
        if(StringUtils.isNotBlank(answersDescDto.getCommentContent())){
            Pattern pattern = Pattern.compile("^.*"+answersDescDto.getCommentContent()+".*$", Pattern.CASE_INSENSITIVE);
            query2.addCriteria(Criteria.where("commentContent").regex(pattern));
        }
        list = mongoTemplate.find(query2, StudyComment.class);
        list.forEach(model->{
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(model.getWxUserId());
            model.setIcon(feignWxUserDto.getIcon());
            model.setNickname(feignWxUserDto.getNickname());
        });
        Query queryCount = new Query();
        queryCount.addCriteria(Criteria.where("articleId").is(answersDescDto.getId()));
        if(StringUtils.isNotBlank(answersDescDto.getCommentContent())){
            Pattern pattern = Pattern.compile("^.*"+answersDescDto.getCommentContent()+".*$", Pattern.CASE_INSENSITIVE);
            queryCount.addCriteria(Criteria.where("commentContent").regex(pattern));
        }
        long count = mongoTemplate.count(queryCount, "studyCommentCollection");
        JgPageVo jgPageVo = new JgPageVo<>(new PageInfo(list));
        jgPageVo.setCurIndex(answersDescDto.getCurPage());
        jgPageVo.setPageSize(answersDescDto.getMaxPage());
        jgPageVo.setPagesCount((int) count/answersDescDto.getMaxPage());
        jgPageVo.setData(list);
        jgPageVo.setCount(count);
        return new ReturnVO("评论查询成功", jgPageVo);
    }

    public  ReturnVO<JgPageVo<List<StudyAnswersVo>>> getAnswersList(StudyAnswersDto answersDto){
        Long id=answersDto.getUid();
        Query query = new Query();
        query.addCriteria(Criteria.where("wxUserId").is(id));
        query.with(new Sort(Sort.Direction.DESC, "createTime")).with(new PageRequest(answersDto.getCurPage()-1, answersDto.getMaxPage()));
        List<StudyComment> commentList = mongoTemplate.find(query,StudyComment.class);
        ArrayList<StudyAnswersVo> answersVoArrayList = new ArrayList();
        commentList.forEach((comment)->{
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(comment.getWxUserId());
            comment.setIcon(feignWxUserDto.getIcon());
            comment.setNickname(feignWxUserDto.getNickname());

            StudyAnswersVo answersVo = new StudyAnswersVo();
            BeanUtils.copyProperties(comment,answersVo);

            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.eq("id",answersVo.getArticleId());
            StudyQuestionsAnswersList questionsAnswersList = studyQuestionsAnswersListMapper.selectOne(queryWrapper);
            if(questionsAnswersList!=null){
                answersVo.setPublishContent(questionsAnswersList.getPublishContent());
            }else{
                answersVo.setPublishContent("");
            }
            List<String> publishImageUrlList = answersVo.getPublishImageUrlList();
            if(publishImageUrlList!=null){
                answersVo.setUrlListSize(publishImageUrlList.size());
            }else{
                answersVo.setUrlListSize(0);
            }
            QueryWrapper acceptQ = new QueryWrapper();
            acceptQ.eq("accept_id",answersVo.getId());
            Integer isAccept = studyQuestionsAnswersListMapper.selectCount(acceptQ);
            answersVo.setIsAccept(isAccept);
            answersVoArrayList.add(answersVo);
        });

        Query queryCount = new Query();
        queryCount.addCriteria(Criteria.where("wxUserId").is(answersDto.getUid()));
        long count = mongoTemplate.count(queryCount, "studyCommentCollection");
//        questionsContentDescVo.setCommentList(commentList);
        JgPageVo jgPageVo = new JgPageVo<>(new PageInfo(answersVoArrayList));
        jgPageVo.setCurIndex(answersDto.getCurPage());
        jgPageVo.setPageSize(answersDto.getMaxPage());
        jgPageVo.setPagesCount((int) count/answersDto.getMaxPage());
        jgPageVo.setData(answersVoArrayList);
        jgPageVo.setCount(count);
        return new ReturnVO("评论查询成功", jgPageVo);
    }
    public ReturnVO deleteComment(StudyComment comment) {
        StudyComment comment1 = mongoTemplate.findById(comment.getUid(), StudyComment.class);

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(comment.getUid()));
        mongoTemplate.remove(query,StudyComment.class);

        //todo 小程序订阅
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        systemMessageMqDto.setMessageDetail("很抱歉,您的评论"+comment1.getCommentContent()+"因违规已被管理员删除，详情请在小程序内查看");
        systemMessageMqDto.setMessageTitle("学以致用");
        systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
            {
                add(comment1.getWxUserId());
            }
        });
        commentProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO("学以致用评论删除成功", 1);
    }


    public ReturnVO deleteQueAns(StudyQuestionsAnswersList questionsAnswersList) {

        StudyQuestionsAnswersList questionsAnswersList1 = studyQuestionsAnswersListMapper.selectById(questionsAnswersList.getId());

        studyQuestionsAnswersListMapper.deleteById(questionsAnswersList.getId());
        //todo 小程序订阅
        SystemMessageMqDto systemMessageMqDto = new SystemMessageMqDto();
        systemMessageMqDto.setMessageDetail("很抱歉,您发布的文章:"+questionsAnswersList1.getPublishContent()+"因违规已被管理员删除，详情请在小程序内查看");
        systemMessageMqDto.setMessageTitle("学以致用");
        systemMessageMqDto.setWxUserIds(new ArrayList<Long>() {
            {
                add(questionsAnswersList1.getPublishPersonId());
            }
        });
        commentProducer.ackMQSender(JSONObject.toJSONString(systemMessageMqDto));
        return new ReturnVO("学以致用文章删除成功", 1);
    }

}
